package com.alpha.eceasy.extension;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.github.yulichang.base.MPJBaseServiceImpl;

import java.io.Serializable;
import java.util.List;
import java.util.Objects;

public class BaseServiceImpl<M extends BaseSqlMapper<T>, T extends BaseFormInfo<T>> extends MPJBaseServiceImpl<M, T> implements BaseService<T> {
    @Override
    public T getByGuid(Serializable guid) {
        return baseMapper.selectByGuid(guid);
    }

    /**
     * 插入一条记录（选择字段，策略插入）
     *
     * @param entity 实体对象
     */
    @Override
    public boolean save(T entity) {
        return SqlHelper.retBool(getBaseMapper().insertByGuid(entity));
    }

    /**
     * TableId 注解存在更新记录，否插入一条记录
     *
     * @param entity 实体对象
     * @return boolean
     */
    @Override
    public boolean saveOrUpdate(T entity) {
        if (null != entity) {
            TableInfo tableInfo = TableInfoHelper.getTableInfo(super.entityClass);
            Assert.notNull(tableInfo, "error: can not execute. because can not find cache of TableInfo for entity!");
            List<TableFieldInfo> fieldList = tableInfo.getFieldList();
            boolean matchPropertyByGuid = fieldList.stream().map(TableFieldInfo::getProperty).anyMatch("guid"::equals);
            Assert.isTrue(matchPropertyByGuid, "error: can not execute. because can not find column for guid from entity!");
            Object guidVal = tableInfo.getPropertyValue(entity, "guid");
            return StringUtils.checkValNull(guidVal) || Objects.isNull(getByGuid((Serializable) guidVal))
                    ? this.save(entity) : this.updateByGuid(entity);
        }
        return false;
    }

    @Override
    public boolean updateByGuid(T entity) {
        return SqlHelper.retBool(baseMapper.updateByGuid(entity));
    }

    @Override
    public boolean removeByGuid(Serializable guid) {
        return SqlHelper.retBool(baseMapper.deleteByGuid(guid));
    }
}
